package com.glory.brepda.activity.mfg;

import android.view.View;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.glory.brepda.R;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.BomEntity;
import com.glory.brepda.entity.DefectCodeEntity;
import com.glory.brepda.entity.ScrapEntity;
import com.glory.brepda.entity.ToolEntity;
import com.glory.brepda.entity.ToolListEntity;
import com.glory.brepda.entity.ToolUnBindEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.MyUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class ToolUnBindActivity extends BaseActivity {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etToolID)
    FreeUI_ClearEditText etToolID;
    @BindView(R.id.llToolLayout)
    LinearLayout llToolLayout;
    @BindView(R.id.llLotLayout)
    LinearLayout llLotLayout;
    @BindView(R.id.etEqpWorkID)
    FreeUI_ClearEditText etEqpWorkID;
    @BindView(R.id.etComment)
    FreeUI_ClearEditText etComment;
    @BindView(R.id.llCommentLayout)
    LinearLayout llCommentLayout;
    @BindView(R.id.tvToolID)
    TextView tvToolID;
    @BindView(R.id.ivToolIDArrow)
    ImageView ivToolIDArrow;
    @BindView(R.id.flToolIDList)
    FrameLayout flToolIDList;
    @BindView(R.id.llToolListLayout)
    LinearLayout llToolListLayout;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.checkbox)
    CheckBox checkbox;
    @BindView(R.id.tvPosition)
    TextView tvPosition;
    @BindView(R.id.tvReason)
    TextView tvReason;
    @BindView(R.id.ivPositionArrow)
    ImageView ivPositionArrow;
    @BindView(R.id.ivReasonArrow)
    ImageView ivReasonArrow;
    @BindView(R.id.flPositionList)
    FrameLayout flPositionList;
    @BindView(R.id.flReasonList)
    FrameLayout flReasonList;
    @BindView(R.id.llConsumeMainQTY)
    LinearLayout llConsumeMainQTY;
    @BindView(R.id.etConsumeMainQTY)
    FreeUI_ClearEditText etConsumeMainQTY;
    @BindView(R.id.etOtherReason)
    FreeUI_ClearEditText etOtherReason;
    @BindView(R.id.llOtherReason)
    LinearLayout llOtherReason;

    // 治具标准寿命和治具已使用次数显示框
    @BindView(R.id.llToolLimitLife)
    LinearLayout llToolLimitLife;

    // 治具标准寿命
    @BindView(R.id.tvToolLimitLife)
    TextView tvToolLimitLife;

    //
    @BindView(R.id.llToolCurrentCount)
    LinearLayout llToolCurrentCount;

    // 治具已使用次数
    @BindView(R.id.tvToolCurrentCount)
    TextView tvToolCurrentCount;


    //劈刀上机次数
    @BindView(R.id.llRoadNum)
    LinearLayout llRoadNum;
    @BindView(R.id.tvRoadNum)
    TextView tvRoadNum;



    //前次累计实打点数
    @BindView(R.id.llHisRealNum)
    LinearLayout llHisRealNum;
    @BindView(R.id.tvHisRealNum)
    TextView tvHisRealNum;


    //前次累计批次点数
    @BindView(R.id.llHisLotNum)
    LinearLayout llHisLotNum;
    @BindView(R.id.tvHisLotNum)
    TextView tvHisLotNum;

    //当前批次点数
    @BindView(R.id.llCurrLotNum)
    LinearLayout llCurrLotNum;
    @BindView(R.id.tvCurrLotNum)
    TextView tvCurrLotNum;


    //累计实打使用率
    @BindView(R.id.llTotalRealQty)
    LinearLayout llTotalRealQty;
    @BindView(R.id.tvTotalRealQty)
    TextView tvTotalRealQty;



    //累计批次使用率
    @BindView(R.id.UseNumber)
    LinearLayout UseNumber;
    @BindView(R.id.realUsrNumber)
    TextView realUsrNumber;






    // 治具字典，点击需要解绑的治具时，从里面获取治具信息来回显治具的寿命和当前使用的次数
    private HashMap<String, ToolEntity> toolMap;
    private List<String> mToolList;
    private FreeUI_GeneralPop mToolPop;
    private FreeUI_GeneralPop mPositionPop;
    private FreeUI_GeneralPop mReasonPop;
    private List<String> mPositionList;
    private List<String> mReasonList =new ArrayList<>();
    Map<String, String> mReasonMap = new HashMap<>();


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_tool_un_bind;
    }

    @Override
    protected void initView() {
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        llCommentLayout.setVisibility(View.GONE);
        llToolLayout.setVisibility(View.GONE);
        llToolListLayout.setVisibility(View.VISIBLE);
        checkbox.setVisibility(View.VISIBLE);
        llLotLayout.setVisibility(View.GONE);
        llOtherReason.setVisibility(View.GONE);
        setMainLayout(llMain);
        mToolList = new ArrayList<>();
        mPositionList = new ArrayList<>();
        tvReason.setText("正常下机");
        String eqpid = getIntent().getExtras().getString("EQPID");
        if (eqpid != null){
            etEqpWorkID.setText(eqpid);
            requestTool(eqpid);
        }

        initEdit(etEqpWorkID, s -> requestTool(s));
    }



    private void requestTool(String s) {
        FreeUI_EntityCallBack<BaseResponseBean<ToolListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<ToolListEntity>>
                (new TypeToken<BaseResponseBean<ToolListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<ToolListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    List<ToolEntity> toolList = response.body().getResponse().getBody().getTOOLLIST();
                    mToolList.clear();
                    if (toolList.size() > 0) {
                        // 治具有绑定设备，则进行初始化治具字典,根据toolList大小来定义字典，可将装载因子设置为1，减少空间浪费
                        toolMap = new HashMap<>(toolList.size(), 1);
                        for (ToolEntity entity : toolList){
                            mToolList.add(entity.getTOOLID());
                            toolMap.put(entity.getTOOLID(), entity);
                        }
                    }

                }
            }

            @Override
            public void onError(Response<BaseResponseBean<ToolListEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"TOOLREPORT");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE","LOAD");
        map.addProperty("EQUIPMENTID",s);
        NetUtils.requestPostNet("IF.TOOLREPORT","TOOLREPORT",ToolUnBindActivity.this,map,callBack);
    }

    private void requestPositionList(String s) {
        FreeUI_EntityCallBack<BaseResponseBean<ToolUnBindEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<ToolUnBindEntity>>
                (new TypeToken<BaseResponseBean<ToolUnBindEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<ToolUnBindEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                    mPositionList.clear();
                    if (response.body().getResponse().getBody() == null || response.body().getResponse().getBody().getSITE().size() <= 0) {
                        return;
                    }
                    if (response.body().getResponse().getBody().isSTATE()){
                        llConsumeMainQTY.setVisibility(View.VISIBLE);

                    }else {
                        llConsumeMainQTY.setVisibility(View.GONE);

                    }
                    mPositionList.addAll(response.body().getResponse().getBody().getSITE());
                    tvPosition.setText(mPositionList.get(0));

                    if(response.body().getResponse().getBody().getCURRNUM() != null)
                    {
                        tvToolCurrentCount.setText(response.body().getResponse().getBody().getCURRNUM());       //当前实打点数
                    }
                    if(response.body().getResponse().getBody().getUSERATE() != null)
                    {
                        llRoadNum.setVisibility(View.VISIBLE);      //劈刀上机次数
                        tvRoadNum.setText(response.body().getResponse().getBody().getROADNUM());

                        llHisRealNum.setVisibility(View.VISIBLE);   //前次累计实打点数
                        tvHisRealNum.setText(response.body().getResponse().getBody().getHISREALNUM());

                        llHisLotNum.setVisibility(View.VISIBLE);    //前次累计批次点数
                        tvHisLotNum.setText(response.body().getResponse().getBody().getHISLOTNUM());

                        llCurrLotNum.setVisibility(View.VISIBLE);   //当前批次点数
                        tvCurrLotNum.setText(response.body().getResponse().getBody().getCURRLOTNUM());

                        UseNumber.setVisibility(View.VISIBLE);      //累计批次使用率
                        realUsrNumber.setText(response.body().getResponse().getBody().getUSERATE());

                        llTotalRealQty.setVisibility(View.VISIBLE); //累计实打使用率
                        tvTotalRealQty.setText(response.body().getResponse().getBody().getTOTALREALQTY());


                    }
                    else
                    {
                        UseNumber.setVisibility(View.GONE);
                        llRoadNum.setVisibility(View.GONE);
                        llHisRealNum.setVisibility(View.GONE);
                        llCurrLotNum.setVisibility(View.GONE);
                        UseNumber.setVisibility(View.GONE);
                        llTotalRealQty.setVisibility(View.GONE);
                    }

                }
            }

            @Override
            public void onError(Response<BaseResponseBean<ToolUnBindEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"GetStationByEqpId");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("EQUIPMENTID",s);
        map.addProperty("TOOL_CODE",tvToolID.getText().toString());
        map.addProperty("IS_UP",0);
        NetUtils.requestPostNet("GetStationByEqpId","GetStationByEqpId",ToolUnBindActivity.this,map,callBack);
    }

    @Override
    protected void initData() {
//        mReasonList.addAll(Arrays.asList("正常下机","改机", "改工程批次","堵塞","劈刀异常","其他"));
        requesReasonList();
    }

    @OnClick({R.id.tvBaseSubmit,R.id.flToolIDList,R.id.flPositionList,R.id.flReasonList})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.tvBaseSubmit){
//            if (actionControl("Submit22")) {
//                return;
//            }
            if (getText(etEqpWorkID).equals("") || tvToolID.getText().toString().equals("")) {
                showToast("设备号或ToolID不能为空", false);
                return;
            }
            for(Map.Entry<String, String> entry : mReasonMap.entrySet())
            {
                if(tvReason.getText().toString().equals(entry.getKey()))
                {
                    if(entry.getValue().equals("选择后需额外填写原因"))
                    {
                        if(getText(etOtherReason).equals("")){
                            showToast("请输入下机原因说明",false);
                            return;
                        }

                    }
                }
            }
//            if(tvReason.getText().toString()=="其他" && getText(etOtherReason).equals("")){
//                showToast("请输入下机原因",false);
//                return;
//            }

            if(tvReason.getText().toString().equals("")){
                showToast("请选择下机原因",false);
                return;
            }

            FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "确定要提交?", new FreeUI_CommonCallback() {
                @Override
                public void onSuccess() {
                    FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<JSONObject>>
                            (new TypeToken<BaseResponseBean<JSONObject>>() {
                            }.getType(), getSupportFragmentManager(), this) {

                        @Override
                        public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                            super.onSuccess(response);
                            if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
   //                             qcInfo();
                                showToast("解绑成功",true);
                                finish();
                            }
                        }

                        @Override
                        public void onError(Response<BaseResponseBean<JSONObject>> response) {
                            super.onError(response);
                            loadError(response.getException(),"TOOLREPORT");
                        }
                    };
                    JsonObject map = new JsonObject();
                    map.addProperty("ACTIONTYPE","DOWN");
                    map.addProperty("EQUIPMENTID",getText(etEqpWorkID));
                    map.addProperty("CONSUMEMAINQTY",getText(etConsumeMainQTY));
                    map.addProperty("REALUSRNUMBER",realUsrNumber.getText().toString());
                    map.addProperty("TOTALREALQTY", tvTotalRealQty.getText().toString());
                    map.addProperty("SITE",tvPosition.getText().toString());
                    for(Map.Entry<String, String> entry : mReasonMap.entrySet()){
                        if(tvReason.getText().toString().equals(entry.getKey())){
                            if(entry.getValue().equals("选择后需额外填写原因"))
                            {
                                map.addProperty("REASON",tvReason.getText().toString());
                                map.addProperty("REASONDETAIL", getText(etOtherReason));
                            }
                            else {
                                map.addProperty("REASON",tvReason.getText().toString());
                            }
                            break;
                        }
                    }
//                    if(tvReason.getText().toString()=="其他"){
//                        map.addProperty("REASON",getText(etOtherReason));
//                    }else{
//                        map.addProperty("REASON",tvReason.getText().toString());
//                    }
                    List<ToolEntity> toolList = new ArrayList<>();
                    ToolEntity toolEntity = new ToolEntity(tvToolID.getText().toString());
                    toolEntity.setSTATE(checkbox.isChecked() ? "SCRAP" : "");
                    toolList.add(toolEntity);
                    map.add("TOOLLIST",new JsonParser().parse(new Gson().toJson(toolList)).getAsJsonArray());
                    NetUtils.requestPostNet("IF.TOOLREPORT","TOOLREPORT",ToolUnBindActivity.this,map,callBack);
                }
            }, () -> {
            }).show(getSupportFragmentManager(),"TOOLREPORT");
        }else if (view.getId() == R.id.flToolIDList){
            if (mToolList.size() <= 0){
                showToast("未获取到tool列表",false);
                return;
            }else {
                showToolPop();
            }

        }else if(view.getId() == R.id.flPositionList){
                if (tvToolID.getText().toString().equals("")){
                    showToast("请先选择toolID",false);
                    return;
                }
                if (mPositionList.size() <= 0){
                    showToast("未获取到站点列表",false);
                    return;
                }

                mPositionPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flPositionList.getWidth(), mPositionList, ivPositionArrow, (codeS, i) -> {
                    tvPosition.setText(codeS);
                });

                if (mPositionPop.isShowing()) {
                    mPositionPop.dismiss();
                } else {
                    FreeApi_PopUtils.setArrowShow(ivPositionArrow);
                    mPositionPop.showAsDropDown(flPositionList, 0, 0);
                }

        }else if(view.getId()==R.id.flReasonList){
            if (mReasonPop != null) {
                if (mReasonPop.isShowing()) {
                    mReasonPop.dismiss();
                }
            } else {
                mReasonPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flReasonList.getWidth(), mReasonList, ivReasonArrow, (codeS, i) -> {
                    tvReason.setText(codeS);

                    if (tvReason.getText().toString().equals("其他")) {
                        llOtherReason.setVisibility(View.VISIBLE);
                    }else{
                        llOtherReason.setVisibility(View.GONE);
                    }
                    boolean shouldShowOtherReason = false;
                    for(Map.Entry<String, String> entry : mReasonMap.entrySet()){
                        if(tvReason.getText().toString().equals(entry.getKey()))
                        {
                            if(entry.getValue().equals("选择后需额外填写原因"))
                            {
                                shouldShowOtherReason = true;
                                break;
                            }
                        }
                    }
                    if(shouldShowOtherReason)
                    {
                        llOtherReason.setVisibility(View.VISIBLE);
                    }
                    else
                    {
                        llOtherReason.setVisibility(View.GONE);
                    }
                });
            }
            FreeApi_PopUtils.setArrowShow(ivReasonArrow);
            mReasonPop.showAsDropDown(flReasonList, 0, 0);
        }

    }

    private void qcInfo(){

        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<JSONObject>>
                (new TypeToken<BaseResponseBean<JSONObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                    showToast("解绑成功",true);
                    finish();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                super.onError(response);
                loadError(response.getException(),"TOOLCHANGE");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("EQUIPMENTID",getText(etEqpWorkID));
        map.addProperty("TOOLID",getText(etToolID));
        map.addProperty("LOTID","");
        map.addProperty("TRANSTYPE","OFF");
        NetUtils.requestPostNet("IF.TOOLCHANGE","Common",ToolUnBindActivity.this,map,callBack);

    }



    private void showToolPop() {
        mToolPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flToolIDList.getWidth(), mToolList, ivToolIDArrow, (codeS, i) -> {
            tvToolID.setText(codeS);
            // 选中治具之后渲染一下它的治具标准寿命和当前使用次数
            setToolLimitLifeAndCurrentCount(toolMap.get(codeS));
            requestPositionList(getText(etEqpWorkID));
        });

        if (mToolPop.isShowing()) {
            mToolPop.dismiss();
        } else {
            FreeApi_PopUtils.setArrowShow(ivToolIDArrow);
            mToolPop.showAsDropDown(flToolIDList, 0, 0);
        }
    }

    private void setToolLimitLifeAndCurrentCount(ToolEntity toolEntity) {
        // 校验是否有内容，有内容的话进行内容的渲染
        if (toolEntity != null) {
            //
            String limitLife = toolEntity.getLIMITLIFE();
            if (StringUtils.isNotEmpty(limitLife)) {
                tvToolLimitLife.setText(limitLife);
            } else {
                MyUtils.clearTextInTextView(tvToolLimitLife);
            }

            String currentCount = toolEntity.getCURRENTCOUNT();
            if (StringUtils.isNotEmpty(currentCount)) {
                tvToolCurrentCount.setText(currentCount);
            } else {
                MyUtils.clearTextInTextView(tvToolCurrentCount);
            }
        }
    }

    private void requesReasonList() {
        FreeUI_EntityCallBack<BaseResponseBean<DefectCodeEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<DefectCodeEntity>>
                (new TypeToken<BaseResponseBean<DefectCodeEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<DefectCodeEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    List<DefectCodeEntity.DefectCode> scrapcodelists = response.body().getResponse().getBody().getADREFLIST();
                    for (DefectCodeEntity.DefectCode code : scrapcodelists) {
                        mReasonList.add(code.getKEY());
                    }
                    for (DefectCodeEntity.DefectCode code : scrapcodelists){
                        String key = code.getKEY();
                        String description = code.getDESCRIPTION();
                        mReasonMap.put(key, description);
                    }

                }

            }

            @Override
            public void onError(Response<BaseResponseBean<DefectCodeEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"ADREFLISTQUERY");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("REFERENCETYPE","USER");
        map.addProperty("REFERENCENAME","ToolUnbindReason");

        NetUtils.requestPostNet("IF.ADREFLISTQUERY","Common", ToolUnBindActivity.this,map,callBack);
    }
}
